package vision.nvhuong.service;

import java.util.List;

import javax.persistence.EntityManager;

import ch.ivyteam.ivy.environment.Ivy;

import vision.nvhuong.dao.PersistenceExecutable;
import vision.nvhuong.dao.StudentDao;
import vision.nvhuong.entity.Student;

public class StudentService {
	private StudentDao studentDao;
	
	public StudentService(StudentDao studetnDao) {
		super();
		this.studentDao = studetnDao;
	}
	
	public List<Student> findAll(){
		
		return new TransactionManager<List<Student>>().execute("findAll", false, new PersistenceExecutable<List<Student>>() {
			
			@Override
			public List<Student> execute(EntityManager em) throws Exception {
				return studentDao.findAll(em);
			}
		});
	}
	
	public Student save(final Student student){
		return new TransactionManager<Student>().execute("save", true, new PersistenceExecutable<Student>() {
			@Override
			public Student execute(EntityManager em) throws Exception {
				//find and update if any	
				Ivy.log().error("id: "+student.getId());
				if(student.getId() != null){
					Student existingStudent = studentDao.findById(student.getId(), em);
					if(existingStudent != null){
						existingStudent.setName(student.getName());
						existingStudent.setSchool(student.getSchool());
						existingStudent.setGPA(student.getGPA());
						return studentDao.merge(existingStudent, em);
					}
				}
				return studentDao.persist(student, em);
				
			}
		});
	}
	
	public Student findStudentById(final Long id){
		return new TransactionManager<Student>().execute("findById", false, new PersistenceExecutable<Student>() {
			@Override
			public Student execute(EntityManager em) throws Exception {
				return studentDao.findById(id, em);
			}
		});
	}
	
	public Student remove(final Student student){
		return new TransactionManager<Student>().execute("remove", true, new PersistenceExecutable<Student>() {
			@Override
			public Student execute(EntityManager em) throws Exception {
				return studentDao.remove(student, em);
			}
		});
	}

}
